package com.roger.homecenterscreen.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.StrokeCap
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.roger.homecenterscreen.voice.VoiceState
import com.roger.homecenterscreen.voice.SynthesisState
import com.roger.homecenterscreen.voice.getPrimaryColor
import com.roger.homecenterscreen.voice.getEmoji
import com.roger.homecenterscreen.voice.shouldAnimate
import kotlin.math.sin

/**
 * 紧凑的语音状态面板 - 用于右下角显示
 */
@Composable
fun VoiceStatusPanel(
    voiceState: VoiceState,
    synthesisState: SynthesisState,
    recognitionResult: String,
    modifier: Modifier = Modifier
) {
    // 只在非空闲状态或有识别结果时显示
    if (voiceState == VoiceState.IDLE && recognitionResult.isEmpty()) {
        return
    }
    
    Card(
        modifier = modifier,
        colors = CardDefaults.cardColors(
            containerColor = Color.Black.copy(alpha = 0.8f)
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 12.dp, vertical = 8.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            // 左边：状态图标
            VoiceStatusIcon(
                voiceState = voiceState,
                synthesisState = synthesisState
            )
            
            // 右边：文字内容
            Column(
                modifier = Modifier.weight(1f)
            ) {
                // 状态描述
                Text(
                    text = getCompactStateText(voiceState, synthesisState),
                    color = Color.White,
                    fontSize = 11.sp,
                    fontWeight = FontWeight.Medium
                )
                
                // 识别结果
                if (recognitionResult.isNotEmpty()) {
                    Text(
                        text = recognitionResult,
                        color = Color.White.copy(alpha = 0.9f),
                        fontSize = 10.sp,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis
                    )
                }
            }
        }
    }
}

/**
 * 语音状态图标
 */
@Composable
private fun VoiceStatusIcon(
    voiceState: VoiceState,
    synthesisState: SynthesisState
) {
    Box(
        modifier = Modifier.size(32.dp),
        contentAlignment = Alignment.Center
    ) {
        when (voiceState) {
            VoiceState.IDLE -> {
                IdleIcon()
            }
            VoiceState.LISTENING_WAKEUP -> {
                WaitingIcon()
            }
            VoiceState.WAKEUP_DETECTED -> {
                WakeupIcon()
            }
            VoiceState.LISTENING_SPEECH, VoiceState.RECORDING, VoiceState.ASR_START, VoiceState.RECOGNIZING -> {
                ListeningIcon()
            }
            VoiceState.PROCESSING -> {
                ProcessingIcon()
            }
            VoiceState.SPEAKING -> {
                SpeakingIcon(synthesisState)
            }
            VoiceState.ERROR -> {
                ErrorIcon()
            }
        }
    }
}

@Composable
private fun IdleIcon() {
    Box(
        modifier = Modifier
            .size(24.dp)
            .background(
                color = VoiceState.IDLE.getPrimaryColor().copy(alpha = 0.6f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.IDLE.getEmoji(),
            fontSize = 12.sp
        )
    }
}

@Composable
private fun WaitingIcon() {
    val infiniteTransition = rememberInfiniteTransition(label = "waiting")
    val alpha by infiniteTransition.animateFloat(
        initialValue = 0.4f,
        targetValue = 1.0f,
        animationSpec = infiniteRepeatable(
            animation = tween(1500),
            repeatMode = RepeatMode.Reverse
        ),
        label = "alpha"
    )
    
    Box(
        modifier = Modifier
            .size(24.dp)
            .background(
                color = VoiceState.LISTENING_WAKEUP.getPrimaryColor().copy(alpha = alpha * 0.7f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.LISTENING_WAKEUP.getEmoji(),
            fontSize = 12.sp
        )
    }
}

@Composable
private fun WakeupIcon() {
    val infiniteTransition = rememberInfiniteTransition(label = "wakeup")
    val scale by infiniteTransition.animateFloat(
        initialValue = 1.0f,
        targetValue = 1.2f,
        animationSpec = infiniteRepeatable(
            animation = tween(200),
            repeatMode = RepeatMode.Reverse
        ),
        label = "scale"
    )
    
    Box(
        modifier = Modifier
            .size(24.dp)
            .scale(scale)
            .background(
                color = VoiceState.WAKEUP_DETECTED.getPrimaryColor().copy(alpha = 0.8f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.WAKEUP_DETECTED.getEmoji(),
            fontSize = 12.sp
        )
    }
}

@Composable
private fun ListeningIcon() {
    val infiniteTransition = rememberInfiniteTransition(label = "listening")
    val scale by infiniteTransition.animateFloat(
        initialValue = 0.9f,
        targetValue = 1.1f,
        animationSpec = infiniteRepeatable(
            animation = tween(800),
            repeatMode = RepeatMode.Reverse
        ),
        label = "scale"
    )
    
    Box(
        modifier = Modifier
            .size(24.dp)
            .scale(scale)
            .background(
                color = VoiceState.LISTENING_SPEECH.getPrimaryColor().copy(alpha = 0.8f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.LISTENING_SPEECH.getEmoji(),
            fontSize = 12.sp
        )
    }
}

@Composable
private fun ProcessingIcon() {
    val infiniteTransition = rememberInfiniteTransition(label = "processing")
    val rotation by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 360f,
        animationSpec = infiniteRepeatable(
            animation = tween(1500, easing = LinearEasing)
        ),
        label = "rotation"
    )
    
    val scale by infiniteTransition.animateFloat(
        initialValue = 0.9f,
        targetValue = 1.1f,
        animationSpec = infiniteRepeatable(
            animation = tween(1000),
            repeatMode = RepeatMode.Reverse
        ),
        label = "scale"
    )
    
    Box(
        modifier = Modifier
            .size(24.dp)
            .scale(scale)
            .background(
                color = VoiceState.PROCESSING.getPrimaryColor().copy(alpha = 0.8f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.PROCESSING.getEmoji(),
            fontSize = 12.sp
        )
    }
}

@Composable
private fun SpeakingIcon(synthesisState: SynthesisState) {
    val infiniteTransition = rememberInfiniteTransition(label = "speaking")
    
    // 音波动画
    val wavePhase by infiniteTransition.animateFloat(
        initialValue = 0f,
        targetValue = 2 * Math.PI.toFloat(),
        animationSpec = infiniteRepeatable(
            animation = tween(800, easing = LinearEasing)
        ),
        label = "wave"
    )
    
    Box(
        modifier = Modifier.size(32.dp),
        contentAlignment = Alignment.Center
    ) {
        // 音波效果
        Canvas(modifier = Modifier.fillMaxSize()) {
            drawCompactSoundWave(wavePhase)
        }
        
        // 中心图标
        Box(
            modifier = Modifier
                .size(20.dp)
                .background(
                    color = VoiceState.SPEAKING.getPrimaryColor().copy(alpha = 0.9f),
                    shape = CircleShape
                ),
            contentAlignment = Alignment.Center
        ) {
            Text(
                text = VoiceState.SPEAKING.getEmoji(),
                fontSize = 10.sp
            )
        }
    }
}

private fun DrawScope.drawCompactSoundWave(phase: Float) {
    val centerX = size.width / 2
    val centerY = size.height / 2
    val baseRadius = 10.dp.toPx()
    
    for (i in 1..2) {
        val radius = baseRadius + i * 4.dp.toPx() + 
                    3.dp.toPx() * sin(phase + i * 0.7f)
        
        drawCircle(
            color = Color.Cyan.copy(alpha = 0.4f / i),
            radius = radius,
            center = androidx.compose.ui.geometry.Offset(centerX, centerY),
            style = androidx.compose.ui.graphics.drawscope.Stroke(
                width = 1.5.dp.toPx(),
                cap = StrokeCap.Round
            )
        )
    }
}

@Composable
private fun ErrorIcon() {
    Box(
        modifier = Modifier
            .size(24.dp)
            .background(
                color = VoiceState.ERROR.getPrimaryColor().copy(alpha = 0.8f),
                shape = CircleShape
            ),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = VoiceState.ERROR.getEmoji(),
            fontSize = 12.sp
        )
    }
}

/**
 * 获取紧凑状态文字描述
 */
private fun getCompactStateText(voiceState: VoiceState, synthesisState: SynthesisState): String {
    return when (voiceState) {
        VoiceState.IDLE -> "就绪"
        VoiceState.LISTENING_WAKEUP -> "等待唤醒..."
        VoiceState.WAKEUP_DETECTED -> "已唤醒"
        VoiceState.LISTENING_SPEECH, VoiceState.RECORDING, VoiceState.ASR_START, VoiceState.RECOGNIZING -> "正在聆听..."
        VoiceState.PROCESSING -> "AI思考中..."
        VoiceState.SPEAKING -> when (synthesisState) {
            SynthesisState.SYNTHESIZING -> "生成语音中..."
            else -> "正在回答..."
        }
        VoiceState.ERROR -> "语音异常"
    }
}